package com.futures.investm;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.Toast;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.futures.investm.fragment.CommunityFragment;
import com.futures.investm.fragment.HomeNewFragment;
import com.futures.investm.fragment.MarketFragment;
import com.futures.investm.fragment.MineFragment;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;

import tech.com.commoncore.base.BaseActivity;
import tech.com.commoncore.entity.TabEntity;

public class MainActivity extends BaseActivity {

    CommonTabLayout mMainTab;

    private static final String TAB_HOME_FRAGMENT = "home";
    private static final String TAB_KETANG = "discover";
    private static final String TAB_SHUFANG = "note";
    private static final String TAB_MINE_FRAGMENT = "mine";

    private String[] mTitles = {"首页", "日历", "行情", "我的"};
    private int[] mIconSelectIds = {R.mipmap.shouye, R.mipmap.table_biquan_sel, R.mipmap.table_hangqing_sel, R.mipmap.table_diantai_sel};
    private int[] mIconUnselectIds = { R.mipmap.shouye_nor, R.mipmap.table_biquan_nor,R.mipmap.table_hangqing_nor, R.mipmap.table_diantai_nor};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private HomeNewFragment mHomeFragment;
    private CommunityFragment mCommunityFragment;
    private MarketFragment mDiscoverFragment;
//    private NewsFlashFragment mNoteFragment;
    private MineFragment mMineFragment;

    private FragmentManager mFragmentManager;

    private int mCurrentIndex;

    private FragmentTransaction mTransaction;

    @Override
    public int getContentLayout() {
        return R.layout.activity_main;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).init();
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        mMainTab = findViewById(R.id.main_tab);
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        mMainTab.setTabData(mTabEntities);
        mMainTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switchToFragment(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        mFragmentManager = getSupportFragmentManager();

        //如果是从崩溃中恢复，还需要加载之前的缓存
        if (savedInstanceState != null) {
            restoreFragment(savedInstanceState);
        } else {
            switchToFragment(0);
        }


    }


    /**
     * 如果fragment因为内存不够或者其他原因被销毁掉，在这个方法中执行恢复操作
     */
    private void restoreFragment(Bundle savedInstanceState) {
        mCurrentIndex = savedInstanceState.getInt("index");
        mHomeFragment = (HomeNewFragment) mFragmentManager.findFragmentByTag(TAB_HOME_FRAGMENT);
        mDiscoverFragment = (MarketFragment) mFragmentManager.findFragmentByTag(TAB_KETANG);
        mCommunityFragment = (CommunityFragment) mFragmentManager.findFragmentByTag(TAB_SHUFANG);
        mMineFragment = (MineFragment) mFragmentManager.findFragmentByTag(TAB_MINE_FRAGMENT);
        switchToFragment(mCurrentIndex);
    }

    /**
     * 执行切换fragment 的操作
     * 注意：
     * 1. 切换页面的时候，还要调用showBottomBar来保证底部导航栏的显示
     *
     * @param index
     */
    private void switchToFragment(int index) {
        mTransaction = mFragmentManager.beginTransaction();
        hideAllFragments(mTransaction);
        switch (index) {
            case 0:
                showHomeFragment();
                break;
            case 1:
                showNewsFragment();
                break;
            case 2:
                showMarketFragment();
                break;
            case 3:
                showMineFragment();
                break;
        }
        mCurrentIndex = index;
        mTransaction.commit();
    }

    /**
     * 隐藏所有的fragment，并且取消所有的底部导航栏的icon的高亮状态
     *
     * @param transaction
     */
    private void hideAllFragments(FragmentTransaction transaction) {
        if (mCommunityFragment != null) {
            transaction.hide(mCommunityFragment);
        }

        if (mDiscoverFragment != null) {
            transaction.hide(mDiscoverFragment);
        }

        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }

    }

    /**
     * 切换到首页模块
     */
    private void showHomeFragment() {
        if (mHomeFragment == null) {
            mHomeFragment = HomeNewFragment.newInstance();
            mTransaction.add(R.id.fl_main_content, mHomeFragment, TAB_HOME_FRAGMENT);
        } else {
            mTransaction.show(mHomeFragment);
        }
    }

    /**
     * 切换到行情
     */
    private void showMarketFragment() {
        if (mDiscoverFragment == null) {
            mDiscoverFragment = mDiscoverFragment.newInstance();
            mTransaction.add(R.id.fl_main_content, mDiscoverFragment, TAB_KETANG);
        } else {
            mTransaction.show(mDiscoverFragment);
        }
    }

    /**
     * 切换到币圈
     */
    private void showNewsFragment() {
        if (mCommunityFragment == null) {
            mCommunityFragment = mCommunityFragment.newInstance();
            mTransaction.add(R.id.fl_main_content, mCommunityFragment, TAB_SHUFANG);
        } else {
            mTransaction.show(mCommunityFragment);
        }
    }


    /**
     * 切换到我的
     */
    private void showMineFragment() {
        if (mMineFragment == null) {
            mMineFragment = mMineFragment.newInstance();
            mTransaction.add(R.id.fl_main_content, mMineFragment, TAB_MINE_FRAGMENT);
        } else {
            mTransaction.show(mMineFragment);
        }
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再次点击退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        ImmersionBar.with(this).destroy();
        super.onDestroy();
    }
}
